package com.far.permisions.tools;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.crypto.digest.DigestUtil;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;

public class GroovyScriptTools {
    private static final GroovyClassLoader loader = new GroovyClassLoader();

    private static final Cache<String, Class<?>> scriptCache = CacheUtil.newLFUCache(8);

    private static final String functionName = "call";

    public static Object invoke(String scriptText, Object... params) throws Exception {
        Class<?> groovyClass;
        String cacheKey = DigestUtil.md5Hex(scriptText);

        if (scriptCache.containsKey(cacheKey)) {
            groovyClass = scriptCache.get(cacheKey);
        } else {
            groovyClass = loader.parseClass(scriptText);
            scriptCache.put(cacheKey, groovyClass);
        }

        GroovyObject groovyObj = (GroovyObject) groovyClass.getDeclaredConstructor().newInstance();
        return groovyObj.invokeMethod(functionName, params);
    }

}
